package com.lagou.homework.annotations;

import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

public class SecurityHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object h) {

        Handler handler = (Handler) h;

        // 1. 方法或者相应的类是否注解@Security
        Class<?> controllerClass = handler.getController().getClass();
        Method method = handler.getMethod();


        if (!controllerClass.isAnnotationPresent(Security.class)
                && !method.isAnnotationPresent(Security.class)) {
            // 没有注解直接返回true
            return true;
        }

        // 2. 获取用户名
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] usernames = parameterMap.get("username");
        if (usernames.length == 0) {
            return false;
        }

        // 3. 获取授权列表
        Security annotation = method.getAnnotation(Security.class);
        if (annotation == null) {
            annotation = controllerClass.getAnnotation(Security.class);
        }

        Set<String> authorization = new HashSet<>(Arrays.asList(annotation.value()));

        // 4. 判断用户是否授权
        for (String username : usernames) {
            if (authorization.contains(username)) {
                return true;
            }
        }

        try {
            response.getWriter().write("403 no permission");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
